Efficiency of iterators and alternatives? [migrated]

Posted by user48037 on Game Development See other posts from Game Development or by user48037
Published on 2014-06-11T22:34:11Z Indexed on 2014/06/12 3:53 UTC
Read the original article Hit count: 154

Filed under:
|
|

I have the following code for my game tiles:

std::vector<GameObject_Tile*>::iterator it;
for(int y = 0; y < GAME_TILES_Y; y++)
{
for(int x = 0; x < GAME_TILES_X; x++)
{
for (it = gameTiles[x][y].tiles.begin() ; it != gameTiles[x][y].tiles.end(); ++it)
{}}}

tiles is:

struct Game_Tile
{
    // More specific object types will be added here eventually
    vector<GameObject_Tile*> tiles;
};

My problem is that if I change the vector to just be a single GameObject_Tile* instead and remove the iterator line in the loop I go from about 200fps to 450fps.

Some context: The vector/pointer only contains one object in both scenarios. I will eventually need to store multiple, but for testing I just set it to a single pointer.

The loop goes through 2,300 objects each frame and draws them. I would like to point out that if I remove the Draw (not seen int he example) method, I gain about 30 frames in both scenarios, the issue is the iteration.

So I am wondering why having this as a vector being looped through by an iterator (to get at a single object) is costing me over 200 frames when compared to it being a single pointer?

The 200+ frames faster code is:

std::vector<GameObject_Tile*>::iterator it;
for(int y = 0; y < GAME_TILES_Y; y++)
{
for(int x = 0; x < GAME_TILES_X; x++)
{
//gameTiles[x][y].tiles is used as a pointer here instead of using *it
}}

tiles is:

struct Game_Tile
{
    // More specific object types will be added here eventually
    GameObject_Tile* tiles;
};

© Game Development or respective owner

Related posts about c++

Related posts about directx11